﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FantastPlatform.Framework.IService;
using FantastPlatform.Framework.IModel;
using FantastPlatform.Framework.Model;
using NHibernate;
using System.Data;
using FantastPlatform.Framework.Common;
using System.Data.SqlClient;


namespace FantastPlatform.Framework.Service
{
    internal class PermissionService : DataService<IPermission, Permission>, IPermissionService
    {

        #region IPermissionService 成员

        public IList<IRole> GetRolesByPermissionId(int permissionId)
        {
            return Session.CreateQuery("from Permission f left join fetch f.Roles where f.Id=:permissionId").SetInt32("permissionId", permissionId).UniqueResult<IPermission>().Roles;
        }

        public IResource GetResourceByPermissionId(int permissionId)
        {
            return Session.CreateQuery("from Permission p left join fetch p.Resource where p.Id=:permissionId").SetInt32("permissionId", permissionId).UniqueResult<IPermission>().Resource;
        }

        public IOperation GetOperationByPermissionId(int permissionId)
        {
            return Session.CreateQuery("from Permission p left join fetch p.Action where p.Id=:permissionId").SetInt32("permissionId", permissionId).UniqueResult<IPermission>().Operation;
        }
        public override object Create(IPermission entity)
        {
            object id = 0;
            ITransaction transaction = null;
            try
            {
                transaction = Session.BeginTransaction();
                Check.Require<ArgumentNullException>(entity != null, "许可不能为空！");
                Check.Require<ArgumentNullException>(entity.Resource != null, "许可的资源不能为空！");
                Check.Require<ArgumentNullException>(entity.Operation!=null,"许可的操作不能为空！");
                
            }
            catch (System.Exception e)
            {
                if (transaction != null)
                    transaction.Rollback();
                throw e;
            }
            finally
            {
                if (Session != null)
                    Session.Close();
                
            }
            return id;
        }
        public override void DeleteReally(List<int> ids)
        {
            List<string> tables = new List<string>();
            tables.Add("User_RolePermission");
            base.DeleteReallyAndRelations(ids,tables);
        }
        public void UpdateWithUser(IPermission permission)
        {
            Check.Require<ArgumentNullException>(permission != null, "许可不能为空!");
            Check.Require<ArgumentNullException>(permission.Roles.Count>0, "当前许可下的角色不能为空");
            ITransaction transaction = null;
            try
            {
                transaction = Session.BeginTransaction();
                //Session.Update(permission);
                Session.CreateSQLQuery(string.Format("delete from RolePermission where PermissionId={0}", permission.Id)).ExecuteUpdate();
                IDbCommand command = Session.Connection.CreateCommand();
                transaction.Enlist(command);
                DataTable dataTable = new DataTable();
                dataTable.Columns.Add("RoleId");
                dataTable.Columns.Add("PermissionId");
                foreach (IRole role in permission.Roles )
                {
                    DataRow dataRow = dataTable.NewRow();
                    dataRow["RoleId"] = role.Id;
                    dataRow["PermissionId"] =permission.Id;
                    dataTable.Rows.Add(dataRow);
                }
                command.CommandText = "insert into RolePermission(RoleId,PermissionId) values(@RoleId,@PermissionId)";
                SqlParameter roleId = new SqlParameter();
                roleId.ParameterName = "@RoleId";
                roleId.SqlDbType = SqlDbType.Int;
                roleId.SourceColumn = "RoleId";
                SqlParameter PermissionId = new SqlParameter();
                PermissionId.ParameterName = "@PermissionId";
                PermissionId.SqlDbType = SqlDbType.Int;
                PermissionId.SourceColumn = "PermissionId";
                command.Parameters.Add(roleId);
                command.Parameters.Add(PermissionId);
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
                sqlDataAdapter.InsertCommand = command as SqlCommand;
                sqlDataAdapter.Update(dataTable);
                transaction.Commit();
            }
            catch (System.Exception e)
            {
                if (transaction != null)
                {
                    transaction.Rollback();
                }
                throw e;
            }
            finally
            {
                if (Session != null)
                    Session.Close();
            }
        }

        #endregion
    }
}
